package com.corpgovernment.common.utils;

import com.corpgovernment.common.base.Page;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.ctrip.corp.obt.generic.utils.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;

public class PageUtils {

    public static <T> Page toPage(List<T> list) {
        PageInfo pageInfo = new PageInfo<T>(list);
        return new Page(pageInfo.getPageNum(), pageInfo.getPageSize(), pageInfo.getPages(), pageInfo.getTotal(), list);
    }

    public static <T, V> Page<V> optPageBy(List<T> list, Class<V> targetClass) {
        if (CollectionUtils.isEmpty(list)) {
            list = Lists.newArrayList();
        }
        PageInfo pageInfo = new PageInfo<T>(list);
        return new Page(pageInfo.getPageNum(), pageInfo.getPageSize(), pageInfo.getPages(), pageInfo.getTotal(), ListUtils.copyList(list, targetClass));
    }

    public static <T> Page<T> build(PageInfo<T> pageInfo) {
        Page<T> page = new Page<>();
        page.setList(pageInfo.getList());
        page.setTotalPage(pageInfo.getPages());
        page.setCount(pageInfo.getTotal());
        page.setPageSize(pageInfo.getPageSize());
        page.setPageNum(pageInfo.getPageNum());
        return page;
    }

    public static <T, R> Page<R> build(PageInfo<T> pageInfo, Function<T, R> mapper) {
        Page<T> srcPage = build(pageInfo);
        List<R> tgtData = Optional.ofNullable(srcPage.getList()).orElse(new ArrayList<>()).stream().map(mapper).collect(Collectors.toList());
        Page<R> tgtPage = new Page<>();
        tgtPage.setPageNum(srcPage.getPageNum());
        tgtPage.setPageSize(srcPage.getPageSize());
        tgtPage.setCount(srcPage.getCount());
        tgtPage.setTotalPage(srcPage.getTotalPage());
        tgtPage.setList(tgtData);
        return tgtPage;
    }
}
